﻿///// FoobarLearningAgreement /////

using System;
using System.Collections.Generic;
using System.Collections;
//using System.Linq;
using System.Text;
using System.IO;
using System.util;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.events;

namespace FoobarLearningAgreement
{
    class Program
    {
        private class add_event : IPdfPTableEvent
        {
            public void TableLayout(PdfPTable table, float[][] width, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases)
            {
                float[] widths = width[0];
                PdfContentByte cb = canvases[PdfPTable.TEXTCANVAS];
                cb.Rectangle(widths[0], heights[heights.Length - 1], widths[widths.Length - 1] - widths[0], heights[0] - heights[heights.Length - 1]);
                cb.Stroke();
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Chapter 17: example Learning Agreement");
            Console.WriteLine("-> Creates a learning agreement form in PDF;");
            Console.WriteLine("-> resulting PDF: learning_agreement.pdf");
            // step 1: creation of a document-object
            Document document = new Document();
            try
            {
                // step 2:
                // we create a writer
                PdfWriter writer = PdfWriter.GetInstance(
                    // that listens to the document
                        document,
                    // and directs a PDF-stream to a file
                        new FileStream("learning_agreement.pdf", FileMode.Create));

                FieldPositioningEvents fpe = new FieldPositioningEvents();
                writer.PageEvent = fpe;
                // step 3: we open the document
                document.Open();

                StringBuilder js = new StringBuilder("var code = new Array();\nvar name = new Array();\nvar credits = new Array();\n");
                StringBuilder items = new StringBuilder("''");
                StreamReader reader = new StreamReader(@"courses.csv");
                String line;
                int i = 0;

                while ((line = reader.ReadLine()) != null)
                {
                    StringTokenizer js_courses = new StringTokenizer(line, ";");
                    line = js_courses.NextToken();
                    items.Append(", '").Append(line).Append("'");
                    js.Append("code[").Append(i).Append("] = '");
                    js.Append(line).Append("';\n");
                    js.Append("name[").Append(i).Append("] = '");
                    js.Append(js_courses.NextToken()).Append("';\n");
                    js.Append("credits[").Append(i).Append("] = '");
                    js.Append(js_courses.NextToken()).Append("';\n");
                    i++;
                }

                reader.Close();
                js.Append("for (i = 0; i < 16; i++) {\n");
                js.Append("  f = this.getField('course_' + i + '.code');\n");
                js.Append("  f.SetItems([").Append(items.ToString()).Append("]);\n");
                js.Append("  f = this.getField('course_' + i + '.name');\n");
                js.Append("  f.textSize = 0;\n");
                js.Append("  f.multiline = true;\n");
                js.Append("};\n");
                js.Append("this.getField('academic_year').value = '2006-2007';");
                js.Append("this.getField('field_of_study').value = 'ICT';");
                js.Append("this.getField('student_name').SetFocus();");
                js.Append("function updateCourse(event) {\n");
                js.Append("  target = event.target.name;\n");
                js.Append("  parent = target.substring(0, target.length - 5);\n");
                js.Append("  for (c = 0; c < code.length; c++) {\n");
                js.Append("    if (event.value == code[c]) {\n");
                js.Append("         this.getField(parent + '.name').value = name[c];");
                js.Append("         this.getField(parent + '.credits').value = credits[c];");
                js.Append("    }\n");
                js.Append("  }\n");
                js.Append("  this.getField(parent + '.name').SetFocus();");
                js.Append("}\n");
                writer.AddJavaScript(js.ToString());

                // step 4:

                // we create a pushbutton that submits the form
                PdfFormField pushbutton = PdfFormField.CreatePushButton(writer);
                pushbutton.FieldName = "PushMe";
                // we don't define the position on the page yet
                pushbutton.SetWidget(new Rectangle(0, 0), PdfAnnotation.HIGHLIGHT_PUSH);
                pushbutton.Action = PdfAction.CreateSubmitForm(@"learning_agreement.htm", null, 0);
                // we add the button to the FieldPositioningEvent for later use
                fpe.AddField("pushMe", pushbutton);

                Font font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED, 14);
                Paragraph p;

                // TITLE
                p = new Paragraph("EXCHANGE STUDENTS", font);
                p.Alignment = Element.ALIGN_CENTER;
                document.Add(p);
                p = new Paragraph("LEARNING AGREEMENT", font);
                p.Alignment = Element.ALIGN_CENTER;
                document.Add(p);

                // this chunk will generate a field with name academic_year
                Chunk academic_year = new Chunk("                  ");
                academic_year.SetGenericTag("academic_year");
                // this chunk will generate a field with name field_of_study
                Chunk field_of_study = new Chunk("                         ");
                field_of_study.SetGenericTag("field_of_study");

                // SUBTITLE
                p = new Paragraph(30, "ACADEMIC YEAR ", font);
                p.Add(academic_year);
                p.Add(new Phrase(" - FIELD OF STUDY: "));
                p.Add(field_of_study);
                p.Alignment = Element.ALIGN_CENTER;
                document.Add(p);

                // TABLE WITH STUDENT INFORMATION
                PdfPTable table;
                int[] widths = { 12, 16, 8, 14 };
                table = new PdfPTable(4);
                table.SpacingBefore = 10f;
                table.SpacingAfter = 10f;
                add_event ae = new add_event();
                table.TableEvent = ae;
                table.SetWidths(widths);
                table.DefaultCell.Border = PdfPCell.NO_BORDER;
                // first row, first column
                table.AddCell("Name of student:");
                PdfPCell cell;
                // first row, second column: a field to fill in
                cell = new PdfPCell();
                cell.Colspan = 3;
                cell.Border = PdfPCell.NO_BORDER;
                cell.CellEvent = new FieldPositioningEvents(writer, "student_name");
                table.AddCell(cell);
                // second row
                cell = new PdfPCell(new Paragraph("Sending Institution:"));
                cell.Colspan = 4;
                cell.Border = PdfPCell.NO_BORDER;
                table.AddCell(cell);
                // third row, first column
                cell = new PdfPCell();
                cell.PaddingBottom = 5;
                cell.Colspan = 2;
                cell.Border = PdfPCell.NO_BORDER;
                cell.CellEvent = new FieldPositioningEvents(writer, "sending_institution");
                table.AddCell(cell);
                // third row, second column
                cell = new PdfPCell(new Paragraph("Country:"));
                cell.PaddingBottom = 5;
                cell.Border = PdfPCell.NO_BORDER;
                table.AddCell(cell);
                // third row, third column
                cell = new PdfPCell();
                cell.PaddingBottom = 5;
                cell.Border = PdfPCell.NO_BORDER;
                cell.CellEvent = new FieldPositioningEvents(writer, "sending_country");
                table.AddCell(cell);
                // fourth row
                cell = new PdfPCell(new Paragraph("Letter of Introduction:"));
                cell.Colspan = 2;
                cell.Border = PdfPCell.NO_BORDER;
                table.AddCell(cell);
                cell = new PdfPCell();
                cell.Colspan = 2;
                cell.Border = PdfPCell.NO_BORDER;
                TextField letter = new TextField(writer, new Rectangle(0, 0), "letter");
                letter.Options = TextField.FILE_SELECTION;
                PdfFormField introduction = letter.GetTextField();
                introduction.SetAdditionalActions(PdfName.U, PdfAction.JavaScript("this.getField('letter').browseForFileToSubmit();this.getField('receiving_institution').SetFocus();", writer));
                cell.CellEvent = new FieldPositioningEvents(writer, introduction);
                table.AddCell(cell);
                document.Add(table);

                // INFORMATION CONCERNING THE RECEIVING INSTITUTION
                p = new Paragraph("DETAILS OF THE PROPOSED STUDY PROGRAM ABROAD");
                p.Alignment = Element.ALIGN_CENTER;
                document.Add(p);
                table = new PdfPTable(4);
                table.SpacingBefore = 10f;
                table.SpacingAfter = 10f;
                ae = new add_event();
                table.TableEvent = ae;
                table.SetWidths(widths);
                table.DefaultCell.Border = PdfPCell.NO_BORDER;
                // first row
                cell = new PdfPCell(new Paragraph("Receiving Institution:"));
                cell.Colspan = 4;
                cell.Border = PdfPCell.NO_BORDER;
                table.AddCell(cell);
                // second row first column
                cell = new PdfPCell();
                cell.PaddingBottom = 5;
                cell.Colspan = 2;
                cell.Border = PdfPCell.NO_BORDER;
                cell.CellEvent = new FieldPositioningEvents(writer, "receiving_institution");
                table.AddCell(cell);
                // second row, second column
                cell = new PdfPCell(new Paragraph("Country:"));
                cell.PaddingBottom = 5;
                cell.Border = PdfPCell.NO_BORDER;
                table.AddCell(cell);
                // second row, second column
                cell = new PdfPCell();
                cell.PaddingBottom = 5;
                cell.Border = PdfPCell.NO_BORDER;
                cell.CellEvent = new FieldPositioningEvents(writer, "receiving_country");
                table.AddCell(cell);
                document.Add(table);
                // list of courses
                table = new PdfPTable(3);
                ae = new add_event();
                table.TableEvent = ae;
                table.DefaultCell.Border = PdfPCell.RIGHT_BORDER;
                table.AddCell("Course code");
                table.AddCell("Course unit title");
                table.DefaultCell.Border = PdfPCell.NO_BORDER;
                table.AddCell("Number of ECTS credits");
                PdfFormField[] lines = new PdfFormField[16];
                FieldPositioningEvents kid;
                TextField combo;
                PdfFormField comboField;

                for (i = 0; i < 16; i++)
                {
                    lines[i] = PdfFormField.CreateEmpty(writer);
                    lines[i].FieldName = "course_" + i;
                    cell = new PdfPCell();
                    cell.FixedHeight = 22;
                    cell.Border = PdfPCell.RIGHT_BORDER;
                    combo = new TextField(writer, new Rectangle(0, 0), "code");
                    combo.Choices = new String[] { " " };
                    comboField = combo.GetComboField();
                    comboField.SetAdditionalActions(PdfName.K, PdfAction.JavaScript("updateCourse(event);", writer));
                    kid = new FieldPositioningEvents(lines[i], comboField);
                    kid.Padding = 0.5f;
                    cell.CellEvent = kid;
                    table.AddCell(cell);
                    cell = new PdfPCell();
                    cell.FixedHeight = 22;
                    cell.Border = PdfPCell.RIGHT_BORDER;
                    kid = new FieldPositioningEvents(writer, lines[i], "name");
                    kid.Padding = 0.5f;
                    cell.CellEvent = kid;
                    table.AddCell(cell);
                    cell = new PdfPCell();
                    cell.FixedHeight = 22;
                    cell.Border = PdfPCell.NO_BORDER;
                    kid = new FieldPositioningEvents(writer, lines[i], "credits");
                    kid.Padding = 0.5f;
                    cell.CellEvent = kid;
                    table.AddCell(cell);
                }

                document.Add(table);

                for (i = 0; i < 16; i++)
                {
                    writer.AddAnnotation(lines[i]);
                }

                Chunk submit = new Chunk("    Click to submit     ");
                submit.SetGenericTag("pushMe");
                p = new Paragraph(submit);
                p.Alignment = Element.ALIGN_CENTER;
                document.Add(p);
            }

            catch (DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }

            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }

            // step 5: we close the document
            document.Close();

            Console.ReadLine();
        }
    }
}

///// This page is still under construction /////